<template>
  <div class="app-container">
    <div class="category-container">
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="84px">
          <el-form-item label="类目名称" prop="categoryName">
            <el-input
              v-model="queryParams.categoryName"
              placeholder="请输入类目名称"
              clearable
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="main-content">
        <!-- 操作区域 -->
        <div class="action-toolbar">
          <div class="left-actions">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              class="action-btn"
              @click="handleAdd"
              v-hasPermi="['system:category:add']"
            >新增一级类目</el-button>
          </div>
          <div class="right-actions">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </div>
        </div>

        <!-- 树形表格 -->
        <div class="tree-table-wrapper">
          <el-table
            v-loading="loading"
            :data="categoryList"
            row-key="categoryId"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            class="category-table"
            :header-cell-style="headerCellStyle"
            :row-class-name="tableRowClassName"
          >
            <el-table-column label="类目名称" min-width="300">
              <template slot-scope="scope">
                <div class="category-name-cell">
                  <i :class="getCategoryIcon(scope.row)" class="category-icon"></i>
                  <span class="category-name">{{ scope.row.categoryName }}</span>
                  <el-tag v-if="scope.row.children && scope.row.children.length > 0" size="mini" class="level-tag" type="info">
                    {{ getCategoryLevel(scope.row) }}级
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="类目编码" align="center" width="200">
              <template slot-scope="scope">
                <div class="code-container">
                  <span class="code-value">{{ scope.row.categoryId }}</span>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="关联商品/包含子类目" align="center" width="220">
              <template slot-scope="scope">
                <div class="relation-container">
                  <div v-if="scope.row.children && scope.row.children.length > 0" class="relation-item has-children">
                    <i class="el-icon-folder relation-icon"></i>
                    <span>包含 <b>{{ scope.row.children.length }}</b> 个{{ getChildLevelText(scope.row) }}</span>
                  </div>
                  <div v-else class="relation-item has-goods">
                    <i class="el-icon-goods relation-icon"></i>
                    <span>已关联 <b>{{ scope.row.goodsCount || 0 }}</b> 个商品</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="显示顺序" align="center" width="200">
              <template slot-scope="scope">
                <div class="order-container">
                  <span class="order-badge">{{ scope.row.orderNum }}</span>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" align="center" class-name="operation-column" width="220">
              <template slot-scope="scope">
                <div class="operation-container">
                  <el-tooltip content="添加子类目" placement="top">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-plus"
                      circle
                      class="operation-btn"
                      @click="handleAdd(scope.row)"
                      v-hasPermi="['system:category:add']"
                    ></el-button>
                  </el-tooltip>
                  
                  <el-tooltip content="修改类目" placement="top">
                    <el-button
                      size="mini"
                      type="success"
                      icon="el-icon-edit"
                      circle
                      class="operation-btn"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['system:category:edit']"
                    ></el-button>
                  </el-tooltip>
                  
                  <el-tooltip :content="getDeleteTooltip(scope.row)" placement="top">
                    <el-button
                      :disabled="scope.row.children && scope.row.children.length > 0"
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      class="operation-btn"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['system:category:remove']"
                    ></el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 添加或修改类目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="category-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="类目名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入类目名称" />
        </el-form-item>
        
        <el-form-item label="上级类目">
          <div class="parent-category">
            <i v-if="form.parentId > 0" class="el-icon-collection-tag parent-icon"></i>
            <span>{{ form.parentId > 0 ? getParentCategoryName(form.parentId) : '无 (一级类目)' }}</span>
          </div>
        </el-form-item>
        
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-check" @click="submitForm">确 定</el-button>
        <el-button icon="el-icon-close" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from '@/api/system/category';

export default {
  name: 'Category',
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 类目表格数据
      categoryList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        categoryName: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: '类目名称不能为空', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '显示顺序不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 表格头部样式 */
    headerCellStyle() {
      return {
        background: 'linear-gradient(to right, #f0f5ff, #e6f7ff)',
        color: '#3a5a97',
        fontWeight: '600'
      };
    },
    
    /** 表格行样式 */
    tableRowClassName({ row, rowIndex }) {
      const level = this.getCategoryLevel(row);
      return `category-row level-${level}`;
    },
    
    /** 获取类目图标 */
    getCategoryIcon(row) {
      const level = this.getCategoryLevel(row);
      const icons = {
        1: 'el-icon-s-grid',
        2: 'el-icon-s-unfold',
        3: 'el-icon-s-management',
        4: 'el-icon-s-cooperation',
        5: 'el-icon-s-order'
      };
      return icons[level] || 'el-icon-s-operation';
    },
    
    /** 获取类目级别 */
    getCategoryLevel(row) {
      if (!row) return 1;
      let level = 1;
      let parent = row;
      while (parent.parentId !== 0) {
        level++;
        parent = this.findParentNode(this.categoryList, parent.parentId);
      }
      return level;
    },
    
    /** 获取父类目名称 */
    getParentCategoryName(parentId) {
      const parent = this.findParentNode(this.categoryList, parentId);
      return parent ? parent.categoryName : '未知类目';
    },
    
    /** 获取删除按钮提示 */
    getDeleteTooltip(row) {
      return (row.children && row.children.length > 0) 
        ? '无法删除：请先删除子类目' 
        : '删除类目';
    },
    
    /** 查询类目列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = this.handleTree(response.data, 'categoryId', 'parentId');
        this.loading = false;
      });
    },
    
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    
    // 表单重置
    reset() {
      this.form = {
        categoryId: undefined,
        parentId: 0,
        categoryName: undefined,
        orderNum: 0,
        status: '0'
      };
      this.resetForm('form');
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    
    /** 获取子级层级文本 */
    getChildLevelText(row) {
      if (!row) return "一级类目";
      // 获取当前层级
      let level = 1;
      let parent = row;
      while (parent.parentId !== 0) {
        level++;
        parent = this.findParentNode(this.categoryList, parent.parentId);
      }
      
      // 将数字转换为中文
      const numberToChinese = {
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        7: '七',
        8: '八',
        9: '九',
        10: '十'
      };
      
      return `${numberToChinese[level + 1]}级类目`;
    },
    
    /** 获取添加按钮文本 */
    getAddButtonText(row) {
      if (!row) return "一级类目";
      // 获取当前层级
      let level = 1;
      let parent = row;
      while (parent.parentId !== 0) {
        level++;
        parent = this.findParentNode(this.categoryList, parent.parentId);
      }
      
      // 将数字转换为中文
      const numberToChinese = {
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        7: '七',
        8: '八',
        9: '九',
        10: '十'
      };
      
      return `${numberToChinese[level + 1]}级类目`;
    },
    
    /** 递归查找父节点 */
    findParentNode(list, parentId) {
      for (const item of list) {
        if (item.categoryId === parentId) {
          return item;
        }
        if (item.children) {
          const found = this.findParentNode(item.children, parentId);
          if (found) return found;
        }
      }
      return null;
    },
    
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != null && row.categoryId) {
        this.form.parentId = row.categoryId;
      }
      this.open = true;
      this.title = row ? `添加${this.getAddButtonText(row)}` : "添加一级类目";
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getCategory(row.categoryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改类目";
      });
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.categoryId != null) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除类目名称为"' + row.categoryName + '"的数据项？').then(() => {
        return delCategory([row.categoryId]);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
/* 全局变量 */
:root {
  --primary-color: #409EFF;
  --primary-light: #b3d8ff;
  --primary-dark: #337ecc;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --bg-color: #f5f7fa;
  --text-color: #303133;
  --text-secondary: #606266;
  --border-color: #DCDFE6;
  --card-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  --transition-time: 0.3s;
}

.app-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 50px);
}

.category-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: var(--card-shadow);
  overflow: hidden;
}

/* 搜索区域 */
.search-box {
  padding: 15px 20px;
  background: linear-gradient(to right, #ffffff, #f9fbfe);
  border-bottom: 1px solid #ebeef5;
}

/* 内容区域 */
.main-content {
  padding: 20px;
}

/* 操作工具栏 */
.action-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.action-btn {
  background: linear-gradient(135deg, #4776e6, #5a8aef);
  border: none;
  box-shadow: 0 2px 6px rgba(67, 118, 230, 0.2);
  transition: all 0.3s;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(67, 118, 230, 0.3);
}

/* 树形表格样式 */
.tree-table-wrapper {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  overflow: hidden;
}

.category-table {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

/* 类目名称单元格样式 */
.category-name-cell {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.category-icon {
  font-size: 18px;
  margin-right: 8px;
  color: #4776e6;
  background: rgba(71, 118, 230, 0.1);
  padding: 6px;
  border-radius: 4px;
}

.category-name {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
  margin-right: 10px;
}

.level-tag {
  font-size: 10px;
  padding: 0 5px;
  height: 18px;
  line-height: 16px;
  background-color: #f5f7fa;
  color: #909399;
  border-color: #e4e7ed;
}

/* 类目编码样式 */
.code-container {
  display: inline-block;
  background: #f5f7fa;
  padding: 2px 10px;
  border-radius: 12px;
  color: #606266;
  font-family: 'Courier New', monospace;
  font-weight: 600;
  border: 1px solid #ebeef5;
}

/* 关联商品/包含子类目样式 */
.relation-container {
  display: flex;
  justify-content: center;
}

.relation-item {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 4px;
}

.relation-item.has-children {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.relation-item.has-goods {
  background-color: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}

.relation-icon {
  margin-right: 6px;
  font-size: 16px;
}

/* 显示顺序样式 */
.order-container {
  display: flex;
  justify-content: center;
}

.order-badge {
  display: inline-block;
  background: linear-gradient(135deg, #f2f6fc, #edf3fa);
  padding: 2px 10px;
  border-radius: 12px;
  color: #409eff;
  font-weight: 600;
  border: 1px solid #e6effd;
  min-width: 40px;
  text-align: center;
}

/* 操作按钮样式 */
.operation-container {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.operation-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  font-size: 14px;
  transition: all 0.3s;
}

.operation-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格行级别样式 */
::v-deep .category-row.level-1 {
  background-color: rgba(247, 250, 255, 0.6);
}

::v-deep .category-row.level-2 {
  background-color: rgba(250, 252, 255, 0.4);
}

::v-deep .category-row.level-3 {
  background-color: rgba(252, 254, 255, 0.2);
}

::v-deep .category-row:hover > td {
  background-color: #f0f7ff !important;
}

/* 父类目样式 */
.parent-category {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
}

.parent-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 16px;
}

/* 对话框样式 */
::v-deep .category-dialog .el-dialog__header {
  background: linear-gradient(to right, #f7f9fc, #eef2f9);
  padding: 15px 20px;
  border-bottom: 1px solid #e8eaec;
}

::v-deep .category-dialog .el-dialog__title {
  color: #303133;
  font-weight: 600;
}

::v-deep .category-dialog .el-dialog__body {
  padding: 20px 20px 10px;
}

::v-deep .category-dialog .el-dialog__footer {
  padding: 10px 20px 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .operation-container {
    flex-direction: column;
    gap: 5px;
  }
  
  .category-name-cell {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .category-icon {
    margin-bottom: 5px;
  }
}
</style>
